package com.mesSystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mesSystem.dto.Result;
import com.mesSystem.entity.Employee;
import com.mesSystem.entity.Equipment;
import com.mesSystem.service.impl.EquipmentService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@ResponseBody
@Slf4j
@RequestMapping("equipment")
public class EquipmentController {
    @Autowired
    EquipmentService equipmentService;

    /**
     * 添加
     * @param equipment
     * @return
     */
    @PostMapping("increase")
    public Result increase(@RequestBody Equipment equipment) {
        equipmentService.save(equipment);
        log.info("添加设备:{}",equipment);
        return Result.ok("创建成功");
    }

    /**
     * 删除（本质上设备不可删除，只需记录为出售、销毁、等信息）
     * @param equipmentId
     * @return
     */
    @DeleteMapping("delete")
    public Result delete(Long equipmentId) {
        Equipment equipment = equipmentService.getById(equipmentId);
        if ("在线".equals(equipment.getStatus())) {
            return Result.fail("设备仍在线，不可停用");
        }
        equipment.setStatus("停用");
        update(equipment);
        return Result.ok("设备已停用");
    }

    /**
     * 分页查询信息
     */
    @GetMapping("query")
    public Result query(@RequestParam(value = "page", defaultValue = "1") Integer page,
                        @RequestParam(value = "size", defaultValue = "10") Integer size) {
        // 创建分页器对象
        Page<Equipment> Page = new Page<>(page, size);

        // 调用分页查询方法，将分页器传递给service
        equipmentService.page(Page, new QueryWrapper<Equipment>().orderByAsc("equipment_id"));

        // 从分页器对象中获取分页后的数据
        List<Equipment> equipments = Page.getRecords();

        log.info("被查询信息为：{}", equipments);

        // 返回分页结果
        return Result.ok(equipments);
    }

    /**
     * 更改
     */
    @PostMapping("update")
    public Result update(@RequestBody Equipment equipment) {
        if (equipment.getEquipmentId() == null) {
            return Result.fail("没有设备id！");
        }
        equipmentService.updateById(equipment);
        log.info("update:{}",equipment);
        return Result.ok("更新成功");
    }
}
